package com.gewu.pm.ui.adapter;

import android.content.Context;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.gewu.pm.R;
import com.gewu.pm.app.AppAdapter;
import com.gewu.pm.bean.AttendanceRecordGroupBean;

/**
 * 下属打卡记录外层适配器（按日期分组）
 */
public final class SubordinateAttendanceAdapter extends AppAdapter<AttendanceRecordGroupBean> {

    private SubordinateAttendanceChildAdapter.OnItemActionListener mChildListener;
    private OnItemClickListener mChildItemClickListener;

    public SubordinateAttendanceAdapter(Context context) {
        super(context);
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new ViewHolder();
    }

    public void setOnChildItemActionListener(SubordinateAttendanceChildAdapter.OnItemActionListener listener) {
        mChildListener = listener;
    }

    public void setOnChildItemClickListener(OnItemClickListener listener) {
        mChildItemClickListener = listener;
    }

    private final class ViewHolder extends AppAdapter<AttendanceRecordGroupBean>.ViewHolder {

        private final TextView tvDateGroup;
        private final RecyclerView rvChildList;
        private SubordinateAttendanceChildAdapter mChildAdapter;

        private ViewHolder() {
            super(R.layout.subordinate_clock_in_item);
            
            tvDateGroup = findViewById(R.id.tv_date_group);
            rvChildList = findViewById(R.id.rv_child_list);
            
            // 初始化子RecyclerView
            rvChildList.setLayoutManager(new LinearLayoutManager(getContext()));
            mChildAdapter = new SubordinateAttendanceChildAdapter(getContext());
            
            // ⚠️ 必须在 setAdapter 之前设置监听器
            if (mChildItemClickListener != null) {
                mChildAdapter.setOnItemClickListener(mChildItemClickListener);
            }
            mChildAdapter.setOnItemActionListener(mChildListener);
            
            // 设置Tag，用于在Fragment中获取Adapter
            rvChildList.setTag(mChildAdapter);
            rvChildList.setAdapter(mChildAdapter);
        }

        @Override
        public void onBindView(int position) {
            AttendanceRecordGroupBean bean = getItem(position);
            
            // 日期分组标题
            String date = bean.getDate();
            tvDateGroup.setText(date + " " + getWeekDay(date));
            
            // 只设置子列表数据
            mChildAdapter.setData(bean.getChildList());
        }
        
        /**
         * 获取星期几
         */
        private String getWeekDay(String date) {
            // 简单实现，实际应该根据日期计算
            return "星期三";
        }
    }

}
